// pages/user/info.ts
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from "~/stores/app"
import { doUploadImage, doUpdInfo, doLogOff, doSignOut } from '~/api/user'
import type { userInfoState } from '~/../typings/types/stores/app'
import ActionSheet, { ActionSheetTheme } from 'tdesign-miniprogram/action-sheet/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {} as userInfoState,
    showConfirm: false as boolean,
    dialogKey: 'showConfirm'
  },
  handleAction() {
    ActionSheet.show({
      theme: ActionSheetTheme.List,
      selector: '#t-action-sheet',
      context: this,
      items: [
        {
          label: '未知',
        }, {
          label: '男',
        },
        {
          label: '女',
        },
      ],
    });
  },
  async handleSelected(this: any, e: any) {
    await doUpdInfo({
      gender: e.detail.index
    })
    this.doUserInfo()
  },
  handSign(this: any) {
    doSignOut()
    this.exit()
    wx.reLaunch({
      url: '/pages/login/login'
    })
    console.log('退出登录')
  },
  showDialog(e: any) {
    const { key } = e.currentTarget.dataset;
    this.setData({ [key]: true, dialogKey: key });
  },
  async handConfirm(this: any) {
    await doLogOff()
    this.setUserInfo({})
    this.closeDialog()
    wx.reLaunch({
      url: '/pages/login/login'
    })
  },
  closeDialog(this: any) {
    const { dialogKey } = this.data;
    this.setData({ [dialogKey]: false });
  },
  handUpdName(this: any) {
    this.dialog.open(this.data.userInfo.nickName);
  },
  handSuccess(this: any) {
    this.doUserInfo()
  },
  async avatarChange(this: any, e: any) {
    const data = await doUploadImage(e.detail.avatarUrl)
    await doUpdInfo({
      avatarUrl: data.url
    })
    this.doUserInfo()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(this: any) {
    this.storeBinding = createStoreBindings(this, {
      store,
      fields: {
        userInfo: 'userInfo',
      },
      actions: ['doUserInfo', 'setUserInfo', 'exit']
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady(this: any) {
    this.dialog = this.selectComponent("#dialog");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload(this: any) {
    this.storeBinding.destroyStoreBindings();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})